import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    accountType: undefined,
    root: 0
  }
}

// 私有变量对象
const state = getDefaultState()

//私有变量对应的setter方法
const mutations = {
  RESET_STATE: (state) => {
    // 浅copy
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_accountType: (state, value) => {
    state.accountType = value
  },
  SET_ROOT: (state, value) => {
    state.root = value
  }
}

// 自定义的方法
const actions = {
  // user login
  login({ commit }, userInfo) {

    return new Promise((resolve, reject) => {
      // axios调用
      login(userInfo).then(response => {
        const { data } = response
        console.log(data)
        //放到vuex中存储
        commit('SET_TOKEN', data)
        //放到浏览器的cookie中 ,为何存到浏览器的cookie中,防止用户按F5（刷新）
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取当前用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('数据无效，重新登录.')
        }

        const { name, avatar,permissions, root } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_accountType', permissions)
        commit('SET_ROOT', root)


        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user注销
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        //从cookie中移出令牌
        removeToken()
        //重置路由
        resetRouter()
        //重置 vuex的初始化值
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove 移出令牌
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
